package apis

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	config2 "github.com/go-admin-team/go-admin-core/config"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/config"
	"net/http"
	"strconv"
	"time"
	"tuowei.com/app/admin/models"
	"tuowei.com/app/teacher/service"
	"tuowei.com/app/teacher/service/dto"
	service2 "tuowei.com/common/service"
	"tuowei.com/pkg/util"
)

type Login struct {
	api.Api
	base
}

type TeacherClaims struct {
	models.SysUser
	jwt.StandardClaims
}

func (t Login) Cancellation(ctx *gin.Context) {
	err := t.MakeContext(ctx).MakeOrm().Errors
	if err != nil {
		t.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	//teacher := t.GetTeacherInfo(ctx)
	//t.Orm.Table(models.SysUser{}.TableName()).Where("id = ?", teacher.SysUser.UserId).Update("")

}

func (t Login) Login(ctx *gin.Context) {
	s := service.TeacherLogin{}
	req := new(dto.GetMessageCodeRequest)
	err := t.MakeContext(ctx).
		MakeOrm().
		Bind(req, binding.Default(ctx.Request.Method, ctx.ContentType())).
		MakeService(&s.Service).Errors
	if err != nil {
		t.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	// 用于app上架测试账号
	appTel := config2.Get("ACCOUNT_FOR_APP").Int(0)
	if strconv.Itoa(appTel) != req.Phone {
		// 根据短信
		code, err := config.GetRedisClient().Get(util.MakeMessageCodeKey("teacher", req.Phone)).Result()
		if code != req.Code {
			t.Error(http.StatusInternalServerError, err, "验证码不对或者已经过期")
			return
		}
	}
	// 登陆成功，写入token
	//token := jwt.New(jwt.GetSigningMethod(SigningAlgorithm))
	// 根据tel获取teacher info
	obj := new(models.SysUser)
	err = t.Orm.Where("phone = ?", req.Phone).Where("is_auth_app_login = ?", 1).First(obj).Error
	if err != nil {
		t.Error(http.StatusInternalServerError, err, "用户不存在")
		return
	}
	claim := TeacherClaims{
		SysUser:        *obj,
		StandardClaims: jwt.StandardClaims{},
	}
	now := time.Now()
	claim.StandardClaims.IssuedAt = now.Unix()
	claim.StandardClaims.ExpiresAt = now.Add(time.Duration(config.JwtConfig.Timeout) * time.Second).Unix()
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	tokenStr, err := token.SignedString([]byte(config.JwtConfig.Secret))
	if err != nil {
		t.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	t.Context.JSON(http.StatusOK, gin.H{
		"code":   http.StatusOK,
		"expire": now.Add(time.Duration(config.JwtConfig.Timeout) * time.Second),
		"token":  tokenStr,
	})

}

func (t Login) GetMessageCode(ctx *gin.Context) {
	s := service.TeacherLogin{}
	req := new(dto.GetMessageCodeRequest)
	err := t.MakeContext(ctx).
		MakeOrm().
		Bind(req, binding.Default(ctx.Request.Method, ctx.ContentType())).
		MakeService(&s.Service).
		Errors
	if err != nil {
		t.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	obj := new(models.SysUser)
	err = t.Orm.Where("phone = ?", req.Phone).First(obj).Error
	if err != nil {
		t.Error(http.StatusInternalServerError, err, "用户不存在")
		return
	}
	if obj.IsAuthAppLogin != 1 {
		t.Error(http.StatusInternalServerError, errors.New("用户未授权"), "当前账号尚未授权")
		return
	}
	err = s.GetMessageCode(&service2.AliSms{}, req)
	if err != nil {
		t.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	t.OK(nil, "发送成功")
}
